package jmine.tec.hydra.diagnostician;

import jmine.tec.hydra.dao.HydraRequestDAO;
import jmine.tec.hydra.domain.enumx.HydraRequestType;
import jmine.tec.persist.diagnostician.TransactedDiagnostician;
import jmine.tec.utils.date.IntervalAggregator;

import org.springframework.jmx.export.annotation.ManagedAttribute;

import bancosys.tec.persist.controller.TransactionalController;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;

/**
 * @author Marcio Ribeiro (mmr)
 * @created Dec 2, 2011
 */
public abstract class HydraRequestTimeDiagnostician extends TransactedDiagnostician {

    private static final int DEFAULT_DAYS_TO_CONSIDER = 7;

    private static final String KEY_MIN_TIME = "minTime";

    private static final String KEY_MAX_TIME = "maxTime";

    private static final String KEY_AVG_TIME = "avgTime";

    private static final String KEY_REQUESTS = "requests";

    private int daysToConsider = DEFAULT_DAYS_TO_CONSIDER;

    /**
     * Contructor.
     * 
     * @param controller controller.
     */
    public HydraRequestTimeDiagnostician(TransactionalController controller) {
        super(controller);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean doTransacted(DiagnosisBean bean) {
        HydraRequestDAO dao = this.getController().getDAOFactory().getDAOByClass(HydraRequestDAO.class);
        IntervalAggregator times = dao.findLastHydraRequestTimes(this.daysToConsider, this.getRequestType());

        bean.addDescription("Average time: " + times.getAvgTime() + "ms");
        bean.addDescription("Maximum time: " + times.getMaxTime() + "ms");
        bean.addDescription("Minimum time: " + times.getMinTime() + "ms");
        bean.addDescription("Requests: " + times.getIntervalsAdded());

        bean.putValue(KEY_AVG_TIME, times.getAvgTime());
        bean.putValue(KEY_MAX_TIME, times.getMaxTime());
        bean.putValue(KEY_MIN_TIME, times.getMinTime());
        bean.putValue(KEY_REQUESTS, times.getIntervalsAdded());
        return true;
    }

    /**
     * @return average request time.
     */
    @ManagedAttribute(description = KEY_AVG_TIME)
    public double getAverageTime() {
        return (Double) this.getValue(KEY_AVG_TIME);
    }

    /**
     * @return maximum time for a request.
     */
    @ManagedAttribute(description = KEY_MAX_TIME)
    public long getMaxTime() {
        return (Long) this.getValue(KEY_MAX_TIME);
    }

    /**
     * @return min time for a request.
     */
    @ManagedAttribute(description = KEY_MIN_TIME)
    public long getMinTime() {
        return (Long) this.getValue(KEY_MIN_TIME);
    }

    /**
     * @return min time for a request.
     */
    @ManagedAttribute(description = KEY_REQUESTS)
    public int getRequests() {
        return (Integer) this.getValue(KEY_REQUESTS);
    }

    /**
     * @return tipo de requisicao (entrada / saida).
     */
    protected abstract HydraRequestType getRequestType();
}
